package com.jic.interaction.sign;

import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;

public class SingUtils {
    public static String sign(List<String> values) {
        if (values == null) {
            throw new NullPointerException("values is null");
        }
        values.removeAll(Collections.singleton(null));// remove null
        //排序
        Collections.sort(values);
        StringBuilder sb = new StringBuilder();
        for (String s : values) {
            sb.append(s);
        }
        try {
            MessageDigest md = MessageDigest.getInstance("sha1");
            md.update(sb.toString().getBytes("UTF-8"));
            String sign = bytesToHex(md.digest());
            return sign;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static String bytesToHex(byte[] bytes){
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<bytes.length;i++){

            String hex = Integer.toHexString(bytes[i] & 0XFF);
            if (hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
